import { createRequire } from "module";
const require = createRequire(import.meta.url);
const express = require("express");
const http = require("http");
const WebSocket = require("ws");

const app = express();
const server = http.createServer(app);

var ws = new WebSocket.Server({ server });
ws.on("connection", function (socket) {
  console.log("server connected");
  socket.on("message", function (msg) {
    console.log("server rcv data=" + msg);
    socket.send("server send " + msg);
    // 服务端关闭ws连接
  });
  socket.on("close", function () {
    console.log("server close");
  });

  socket.on("error", function (err) {
    console.log("server error " + err);
  });
  //   console.log("服务端关闭ws连接");
  //   socket.close();
});
// 设置服务监听端口
server.listen(3000, function () {
  console.log("Express and WebSocket server running on http://localhost:3000");
});
